﻿using System;
using Gp.Scripts.Core;
using Helpers;
using UnityEngine;

namespace Gp.Scripts.Core {
    public class FaceToPlayer : MonoBehaviour {
        // [SerializeField] private Collider rangeCollider;
        [SerializeField] private Transform targetObject;
        [SerializeField] private float rotateSpeed = 10f;

        private bool _playerInside = false;

        private void Update() {
            if (!_playerInside || targetObject == null) return;
            var player = ObjectHelper.PlayerCharacter;
            if (player == null) return;

            var dir = targetObject.transform.position - player.transform.position;
            dir.y = 0;
            var qu = Quaternion.LookRotation(dir);
            
            targetObject.transform.rotation = Quaternion.Lerp(targetObject.transform.rotation, qu, rotateSpeed * Time.deltaTime); 
        }


        private void OnTriggerEnter(Collider other) {
            if (!ObjectHelper.IsPlayer(other.gameObject)) return;

            _playerInside = true;
        }

        private void OnTriggerExit(Collider other) {
            if (!ObjectHelper.IsPlayer(other.gameObject)) return;

            _playerInside = false;
        }
    }
}